package cn.nkpro.elcube.plugins.esign;

import cn.nkpro.elcube.co.http.NkAbstractHttpClient;
import cn.nkpro.elcube.co.http.NkHttpResponse;
import cn.nkpro.elcube.plugins.esign.model.PsnAuth;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

public class ESignService extends NkAbstractHttpClient {

    @Autowired
    private ESignProperties signProperties;


    public NkHttpResponse request(String url, Object body) throws ESignDefineException {

        String content = JSON.toJSONString(body);

        System.out.println(content);

        String contentMd5=Encryption.doContentMD5(content);

        //传入生成的bodyMd5,加上其他请求头部信息拼接成字符串
        String message = Encryption.appendSignDataString(
                "POST",
                HeaderConstant.ACCEPT.VALUE(),
                contentMd5,
                HeaderConstant.CONTENTTYPE_JSON.VALUE(),
                HeaderConstant.DATE.VALUE(),
                HeaderConstant.HEADERS.VALUE(),
                url
        );

        //整体做sha256签名
        String reqSignature = Encryption.doSignatureBase64(message, signProperties.getAppSecret());

        Map<String,String> headers = new HashMap<>();
        headers.put("X-Tsign-Open-App-Id",signProperties.getAppId());
        headers.put("X-Tsign-Open-Auth-Mode","Signature");
        headers.put("X-Tsign-Open-Ca-Signature",reqSignature);
        headers.put("X-Tsign-Open-Ca-Timestamp",String.valueOf(System.currentTimeMillis()));
        headers.put("Accept",HeaderConstant.ACCEPT.VALUE());
        headers.put("Content-Type",HeaderConstant.CONTENTTYPE_JSON.VALUE());
        headers.put("Content-MD5",contentMd5);

        return this.doPost(signProperties.getHost() + url, headers, content);
    }

    public static void main(String[] args) {
        ESignService eSign = new ESignService();

        PsnAuth auth = new PsnAuth();
        auth.setPsnAuthConfig(new PsnAuth.PsnAuthConfig());
        auth.getPsnAuthConfig().setPsnAccount("mailxbs@126.com");

        try {
            eSign.request("/v3/psn-auth-url", auth);
        } catch (ESignDefineException e) {
            e.printStackTrace();
        }
    }

}
